package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ApUserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 加载评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //参数校验
        if (dto.getCommentId() ==null){
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        if (dto.getSize() == null || dto.getSize() ==0) {   //设置分页默认值
            dto.setSize(10);
        }
        if (dto.getMinDate() == null){
            dto.setMinDate(new Date());
        }
        //根据条件查询评论回复信息
        //TODO:显示评论
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        //设置排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort).limit(dto.getSize());
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            //没有登录,直接返回评论信息
            return ResponseResult.okResult(apCommentRepays);
        }else {
            //创建评论集合,用于封装查询出来的所有评论
            List<ApCommentRepayVO> ApCommentRepayVOs = new ArrayList<>();
            for (ApCommentRepay comment : apCommentRepays) {
                ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
                BeanUtils.copyProperties(comment, apCommentRepayVO);
                //根据用户id,文章id查询是否有点赞记录
                boolean b = findRepayCommentLikeByCommntIdAndApUserId(comment.getId(),user.getId());
                if (b){
                    apCommentRepayVO.setOperation((short)0);
                }
                ApCommentRepayVOs.add(apCommentRepayVO);
            }
            System.out.println("封装后的~~~"+ApCommentRepayVOs);
            return ResponseResult.okResult(ApCommentRepayVOs);
        }
    }

    private boolean findRepayCommentLikeByCommntIdAndApUserId(String commentId, Integer apUserId) {
        Query query = Query.query(Criteria.where("authorId").is(apUserId).and("commentRepayId").is(commentId));
        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (one != null){
            return true;
        }
        return false;
    }

    @Autowired
    CommentService commentService;
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            log.error("请登录后评论");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //参数校验
        if (dto.getCommentId() == null){
            log.error("回复的当前评论不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (dto.getContent().length() > 140){
            log.error("评论内容不得超过140字");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //查询当前评论是否存在
        ApComment comment = commentService.findCommentById(dto.getCommentId());
        if (comment == null){
            log.error("回复的当前评论不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //保存当前评论信息
        saveApCommentRepay(dto,user.getId());
        //修改当前评论回复数量+1
        updateCommentreply(dto.getCommentId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据评论id将回复数+1
     * @param commentId
     */
    private void updateCommentreply(String commentId) {
        //获取当前评论内容
        Query query = Query.query(Criteria.where("id").is(commentId));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        Integer reply = apComment.getReply()+1;
        apComment.setReply(reply);
        mongoTemplate.save(apComment);
    }

    @Autowired
    ApUserFeign apUserFeign;

    /**
     * 保存评论
     * @param dto
     * @param apUserId
     */
    private void saveApCommentRepay(CommentRepaySaveDTO dto, Integer apUserId) {
        //根据用户id查询用户信息
        ApUser apUser = apUserFeign.findApUserById(apUserId);
        if (apUser == null){
            log.error("查询不到当前用户");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //创建评论信息并保存
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUserId);
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        //保存当前评论
        mongoTemplate.save(apCommentRepay);
    }

    /**
     * 点赞回复评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            log.error("请登录后点赞");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getCommentRepayId() == null){
            log.error("评论内容不见啦~");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (dto.getOperation() != 0 && dto.getOperation() != 1){
            log.error("操作不规范");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //检查评论回复信息是否存在
        boolean b = findApCommentRepayById(dto.getCommentRepayId());
        if (!b){
            log.error("当前评论回复数据不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据操作做对应的处理
        if (dto.getOperation() == 0){//点赞
            saveApCommentRepayLike(user.getId(),dto.getCommentRepayId());
            //修改评论回复点赞数
            updateCommentreplylike(dto.getCommentRepayId(),dto.getOperation());
        }else if (dto.getOperation() == 1){ //取消点赞
            removeApCommentRepayLike(user.getId(),dto.getCommentRepayId());
            updateCommentreplylike(dto.getCommentRepayId(),dto.getOperation());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 将评论回复内容点赞数+1
     * @param commentRepayId
     * @param operation
     */
    private void updateCommentreplylike(String commentRepayId, Short operation) {
        //查询评论回复内容
        Query query = Query.query(Criteria.where("id").is(commentRepayId));
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(query, ApCommentRepay.class);
        //根据类型做出判断
        Integer likes = apCommentRepay.getLikes();
        if (operation == 0){
            likes = apCommentRepay.getLikes()+1;
        }else if (operation == 1){
            likes = apCommentRepay.getLikes()-1;
        }
        apCommentRepay.setLikes(likes);
        //更新保存
        mongoTemplate.save(apCommentRepay);
    }


    private void removeApCommentRepayLike(Integer apUserId, String commentRepayId) {
        //查询当前数据是否存在
        Query query = Query.query(Criteria.where("authorId").is(apUserId).and("commentRepayId").is(commentRepayId));
        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (one != null){   //删除当前数据
            mongoTemplate.remove(one);
        }else{
            log.error("点赞记录不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }

    /**
     * 根据用户id,评论id保存点赞数据
     * @param apUserId
     * @param commentRepayId
     */ 
    private void saveApCommentRepayLike(Integer apUserId, String commentRepayId) {
        //查询当前数据是否存在
        Query query = Query.query(Criteria.where("authorId").is(apUserId).and("commentRepayId").is(commentRepayId));
        ApCommentRepayLike one = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (one == null){   //不存在,创建当前点赞数据
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(apUserId);
            apCommentRepayLike.setCommentRepayId(commentRepayId);
            mongoTemplate.save(apCommentRepayLike);
        }else{ //存在,返回错误信息
            log.error("请勿重复点赞");
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
    }

    /**
     * 根据评论回复Id查询评论回复是否存在
     * @param commentRepayId
     * @return
     */
    private boolean findApCommentRepayById(String commentRepayId) {
        Query query = Query.query(Criteria.where("id").is(commentRepayId));

        ApCommentRepay one = mongoTemplate.findOne(query, ApCommentRepay.class);
        if (one != null){
            return true;
        }
        return false;

    }
}
